package com.lucy.starter.handler;

import cn.hutool.core.lang.Validator;
import com.lucy.starter.constant.HttpStatus;
import com.lucy.starter.domain.ResponseDTO;
import com.lucy.starter.exception.BusinessException;
import com.lucy.starter.exception.ExceptionRule;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 全局异常拦截处理
 */
@Slf4j
@ControllerAdvice
@AllArgsConstructor
public class GlobalExceptionHandler {
    List<ExceptionRule> exceptionRules;
    /**
     * 全局异常处理流程
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseDTO<Object> exceptionHandler(Exception e){
        log.error("error:",e);
        ResponseDTO<Object> handlerRes = null;
        // 遍历服务实现
        for (ExceptionRule rule:exceptionRules){
            handlerRes = rule.exceptionHandler(e);
            if (Validator.isNotEmpty(handlerRes)){
                return handlerRes;
            }
        }
        return ResponseDTO.wrap(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
